package com.bh.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bh.common.utils.DateUtils;
import com.bh.common.utils.SecurityUtils;
import com.bh.common.utils.StringUtils;
import com.bh.common.utils.uuid.IdUtils;
import com.bh.wms.domain.WmsInboundOrder;
import com.bh.wms.domain.WmsInboundOrderDetail;
import com.bh.wms.mapper.WmsInboundOrderDetailMapper;
import com.bh.wms.mapper.WmsInboundOrderMapper;
import com.bh.wms.service.IWmsInboundOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 入库单服务实现
 *
 * @author GPT
 */
@Service
public class WmsInboundOrderServiceImpl extends ServiceImpl<WmsInboundOrderMapper, WmsInboundOrder> implements IWmsInboundOrderService {

    private static final String DEFAULT_STATUS = "created";

    @Autowired
    private WmsInboundOrderDetailMapper inboundOrderDetailMapper;

    @Override
    public WmsInboundOrder selectWmsInboundOrderById(Long id) {
        WmsInboundOrder order = baseMapper.selectById(id);
        if (order != null) {
            List<WmsInboundOrderDetail> details = inboundOrderDetailMapper.selectList(new LambdaQueryWrapper<WmsInboundOrderDetail>()
                    .eq(WmsInboundOrderDetail::getInboundOrderId, id)
                    .orderByAsc(WmsInboundOrderDetail::getLineNo, WmsInboundOrderDetail::getId));
            order.setDetails(details);
        }
        return order;
    }

    @Override
    public List<WmsInboundOrder> selectWmsInboundOrderList(WmsInboundOrder query) {
        LambdaQueryWrapper<WmsInboundOrder> wrapper = new LambdaQueryWrapper<>();
        if (query != null) {
            if (StringUtils.isNotEmpty(query.getOrderNo())) {
                wrapper.eq(WmsInboundOrder::getOrderNo, query.getOrderNo());
            }
            if (StringUtils.isNotEmpty(query.getOrderType())) {
                wrapper.eq(WmsInboundOrder::getOrderType, query.getOrderType());
            }
            if (query.getWarehouseId() != null) {
                wrapper.eq(WmsInboundOrder::getWarehouseId, query.getWarehouseId());
            }
            if (query.getOwnerId() != null) {
                wrapper.eq(WmsInboundOrder::getOwnerId, query.getOwnerId());
            }
            if (StringUtils.isNotEmpty(query.getOrderStatus())) {
                wrapper.eq(WmsInboundOrder::getOrderStatus, query.getOrderStatus());
            }
            if (StringUtils.isNotEmpty(query.getSourceOrderNo())) {
                wrapper.eq(WmsInboundOrder::getSourceOrderNo, query.getSourceOrderNo());
            }
        }
        wrapper.orderByDesc(WmsInboundOrder::getCreateTime);
        return baseMapper.selectList(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertWmsInboundOrder(WmsInboundOrder entity) {
        fillCreateInfo(entity);
        if (StringUtils.isEmpty(entity.getOrderNo())) {
            entity.setOrderNo(buildInboundNo());
        }
        if (StringUtils.isEmpty(entity.getOrderStatus())) {
            entity.setOrderStatus(DEFAULT_STATUS);
        }
        int rows = baseMapper.insert(entity);
        saveDetailList(entity, true);
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateWmsInboundOrder(WmsInboundOrder entity) {
        fillUpdateInfo(entity);
        int rows = baseMapper.updateById(entity);
        saveDetailList(entity, true);
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteWmsInboundOrderByIds(Long[] ids) {
        if (ids == null || ids.length == 0) {
            return 0;
        }
        for (Long id : ids) {
            removeDetails(id);
        }
        return baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteWmsInboundOrderById(Long id) {
        removeDetails(id);
        return baseMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changeStatus(WmsInboundOrder entity) {
        fillUpdateInfo(entity);
        return baseMapper.updateById(entity);
    }

    private void saveDetailList(WmsInboundOrder entity, boolean cleanBefore) {
        if (entity == null || entity.getId() == null) {
            return;
        }
        if (cleanBefore) {
            removeDetails(entity.getId());
        }
        if (CollectionUtils.isEmpty(entity.getDetails())) {
            return;
        }
        Date now = DateUtils.getNowDate();
        String username = SecurityUtils.getUsername();
        int lineNo = 1;
        for (WmsInboundOrderDetail detail : entity.getDetails()) {
            detail.setInboundOrderId(entity.getId());
            if (detail.getLineNo() == null) {
                detail.setLineNo(lineNo++);
            }
            if (detail.getStatus() == null) {
                detail.setStatus(1);
            }
            detail.setCreateName(username);
            detail.setCreateTime(now);
            detail.setModifyName(username);
            detail.setModifyTime(now);
            inboundOrderDetailMapper.insert(detail);
        }
    }

    private void removeDetails(Long orderId) {
        if (orderId == null) {
            return;
        }
        inboundOrderDetailMapper.delete(new LambdaQueryWrapper<WmsInboundOrderDetail>().eq(WmsInboundOrderDetail::getInboundOrderId, orderId));
    }

    private void fillCreateInfo(WmsInboundOrder entity) {
        Date now = DateUtils.getNowDate();
        String username = SecurityUtils.getUsername();
        if (entity.getStatus() == null) {
            entity.setStatus(1);
        }
        entity.setCreateName(username);
        entity.setCreateTime(now);
        entity.setModifyName(username);
        entity.setModifyTime(now);
    }

    private void fillUpdateInfo(WmsInboundOrder entity) {
        entity.setModifyName(SecurityUtils.getUsername());
        entity.setModifyTime(DateUtils.getNowDate());
    }

    private String buildInboundNo() {
        return "IB" + DateUtils.dateTimeNow() + (IdUtils.getSnowNextId() % 1000);
    }
}

